package com.zp.config;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author zp
 * @description
 * @created 2021/11/24 12:41
 */

public class ServerConfig implements ApplicationListener<WebServerInitializedEvent> {
    private static final Log log = LogFactory.getLog(ServerConfig.class);

    private int serverPort;

    /**
     * 获取服务名和端口
     * @return
     */
    public String getHostAndPort(){
        try {
            String host = getHost();
            return "http://" + host +":"+getServerPort();
        } catch (UnknownHostException e) {
            log.error(e);
        }
        return null;
    }

    /**
     * 返回端口
     * @return
     */
    public int getServerPort() {
        return serverPort;
    }

    /**
     * 返回host
     * @return
     * @throws UnknownHostException
     */
    public String getHost() throws UnknownHostException {
        return InetAddress.getLocalHost().getHostAddress();
    }

    @Override
    public void onApplicationEvent(WebServerInitializedEvent event) {
        serverPort = event.getWebServer().getPort();
    }
}
